<?php

namespace Trawind\Basics\Rules;

use Illuminate\Contracts\Validation\Rule;

class Decimal implements Rule
{


    protected $digit;
    protected $min;
    protected $max;
    protected $attribute;


    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct(int $digit = 2, $min = null, $max = null)
    {
        $this->digit = $digit;
        $this->min = $min;
        $this->max = $max;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->attribute = $attribute;

        if (is_float($value) || is_numeric($value)) {
            if (!is_null($this->digit)) {
                $digit = strlen(substr(strrchr($value, '.'), 1));
                $bool = $this->digit >= $digit;

                $minBool = is_null($this->min) ? true : $value > $this->min;
                $maxBool = is_null($this->max) ? true : $value < $this->max;
                return $bool && $minBool && $maxBool;
            }
            return true;
        }
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        $value = __('validation.attributes.'.$this->attribute);
        $attribute = \Illuminate\Support\Str::contains($value, 'validation.attributes') ? $this->attribute : $value;

        if (is_null($this->min) && is_null($this->max)) {
            return ___("validation.decimal.decimal", [
                'attribute' => $attribute,
                'digit' => $this->digit
            ]);
        } else {
            if (is_null($this->max)) {
                return ___("validation.decimal.min", [
                    'attribute' => $attribute,
                    'digit' => $this->digit,
                    'min' => $this->min
                ]);
            } else {
                return ___("validation.decimal.max", [
                    'attribute' => $attribute,
                    'digit' => $this->digit,
                    'min' => $this->min,
                    'max' => $this->max
                ]);
            }
        }
    }
}
